/**
 * 素材表
 * 用户获取微信media_id的url
 * 目前使用微信提供的url(其他素材库过来的素材会同步不了),后期换成cdn图片url
 * @authors 杨兴洲（of2502）
 * @date    2017/5/31 0031 10:04
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */

import {model, Schema} from "mongoose";
import CONFIG from '../config';
import { getOssClient } from '@qianmi/x-site-common/util/oss';
const ossClient = getOssClient(CONFIG.OSS_CONFIG);

let MediaSchema = new Schema({
    appID: {"type": String, "required": true},
    media_id: {"type": String, "required": true},
    url: {"type": String, "required": true},
    aliUrl:{"type": String},
    name: String,
    type: String // image/video/voice
}, {
    timestamps: true,
    toJSON: {
        virtuals: true,
        versionKey: false,
        transform: (doc, ret) => {
            delete ret._id
        }
    }
});
MediaSchema.pre('remove',(doc:any)=>{
    if(doc && doc._doc && doc._doc.aliUrl){
        ossClient.delObject(doc._doc.aliUrl).catch((e)=>{
            console.error(e)
        })
    }
});
MediaSchema.index({media_id: 1});
MediaSchema.index({appID: 1, media_id: 1});

export default model('Media', MediaSchema);
